//
//  QZViewController.m
//  ZBarScan
//
//  Created by QF_iOS on 2017/5/17.
//  Copyright © 2017年 QF_iOS. All rights reserved.
//


#import "QZViewController.h"
#import "ZBarSDK.h"
#import <UIKit/UIKit.h>
#import "YKProductInfo.h"
#import "YKCheckController.h"
#import "YKSound.h"
#import <AVFoundation/AVFoundation.h>


#define SCANVIEW_EdgeTop 40.0
#define SCANVIEW_EdgeLeft 50.0

#define TINTCOLOR_ALPHA 0.2  //浅色透明度
#define DARKCOLOR_ALPHA 0.5  //深色透明度




@interface QZViewController ()<ZBarReaderViewDelegate,AVAudioPlayerDelegate>

@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) UIView *codeLine;
@property (nonatomic, strong) NSTimer *tintColorTimer;// 改变字体颜色的定时器

@property (nonatomic, strong) NSMutableArray *colorArray;//字体颜色的数组

//设置扫描画面
@property (nonatomic, strong) UIView *scanView;
@property (nonatomic, strong) ZBarReaderView *readerView;

@property (nonatomic, strong) UILabel *labIntroudction;
//播放器
@property (nonatomic, strong) AVAudioPlayer *player;
@property (nonatomic, strong) AVAudioPlayer *playerRight;
@end

@implementation QZViewController
{
    UIButton *openButton;
    NSMutableDictionary *_paramsDic;
    NSInteger _count;
    YKSound *_sound;//系统声音的id 取值范围为：1000-2000
}

- (void)viewWillAppear:(BOOL)animated
{
    [self.readerView start];
    [self createTimer];
    [self createLableTintColorTimer];
    [openButton setTitle:@"开启闪光灯" forState:UIControlStateNormal];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = kNavigationMainColor;
    // 自定义返回按钮
    [self createCustomBtn];

    self.colorArray = [NSMutableArray array];
    [self.colorArray addObject:[UIColor redColor]];
    [self.colorArray addObject: [UIColor whiteColor]];
    [self.colorArray  addObject:[UIColor colorWithRealRed:66 green:141 blue:225 alpha:1]];
    
    
    
    [self setScanview];
    
    self.readerView = [[ZBarReaderView alloc] init];
    self.readerView.frame = CGRectMake(0, 64, kScreenWidth, kScreenheight - 64);
    self.readerView.tracksSymbols = NO;
    self.readerView.readerDelegate = self;
    self.readerView.torchMode = 0;
    [self.readerView addSubview:self.scanView];
    [self.view addSubview:self.readerView];
    
    
    // 声音初始化
//    _sound = [[YKSound alloc] initSystemSoundWithName:@"dtmf-pound" SoundType:@"caf"];
    
    //扫描区域
//    self.readerView.scanCrop = CGRectMake(0, 0, 1, 1);
    [self.readerView start];
    
    //定时器
    [self createSoundVideo];
    [self playerRightAction];
    
    _paramsDic = [NSMutableDictionary dictionary];
}

- (void)createSoundVideo {
  
   

    NSError *err;
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"扫描错误提示音" withExtension:@"mp3"];
    //    初始化播放器
    _player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&err];

    //    设置代理
    _player.delegate = self;
    //    设置播放速率
    _player.rate = 1.0;
    //    设置播放次数 负数代表无限循环
    _player.numberOfLoops = 1;
    //    准备播放
    [_player prepareToPlay];
    
    
}
- (void)playerRightAction {
    
    
    
    NSError *err;
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"提示正确" withExtension:@"mp3"];
    //    初始化播放器
    _playerRight = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&err];
    
    //    设置代理
    _playerRight.delegate = self;
    //_playerRight.rate = 1.0;
    //    设置播放次数 负数代表无限循环
    _playerRight.numberOfLoops = 1;
    //    准备播放
    [_playerRight prepareToPlay];
    
    
}




#pragma mark -- ZBarReaderViewDelegate
-(void)readerView:(ZBarReaderView *)readerView didReadSymbols:(ZBarSymbolSet *)symbols fromImage:(UIImage *)image
{
    const zbar_symbol_t *symbol =zbar_symbol_set_first_symbol(symbols.zbarSymbolSet);
    NSString *symbolStr = [NSString stringWithUTF8String: zbar_symbol_get_data(symbol)];
    
    //判断是否包含 头'http:'
    NSString *regex =@"http+:[^\\s]*";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    
    //判断是否包含 头'ssid:'
    NSString *ssid =@"ssid+:[^\\s]*";;
    NSPredicate *ssidPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",ssid];
    
    if ([predicate evaluateWithObject:symbolStr]) {
        
    }
    else if([ssidPre evaluateWithObject:symbolStr]) {
        
        NSArray *arr = [symbolStr componentsSeparatedByString:@";"];
        
        NSArray * arrInfoHead = [[arr  objectAtIndex:0]componentsSeparatedByString:@":"];
        
        NSArray * arrInfoFoot = [[arr  objectAtIndex:1]componentsSeparatedByString:@":"];
        
        
        symbolStr = [NSString stringWithFormat:@"ssid: %@ \n password:%@",
                     [arrInfoHead objectAtIndex:1],[arrInfoFoot objectAtIndex:1]];
        
        UIPasteboard *pasteboard=[UIPasteboard generalPasteboard];
        //然后，可以使用如下代码来把一个字符串放置到剪贴板上：
        pasteboard.string = [arrInfoFoot objectAtIndex:1];
    }
    
    AppDelegate *appdelegate = kAppDelegate;
    
    if (symbolStr) {
        [_paramsDic setObject:symbolStr forKey:@"QRCode"];
    }
    if (appdelegate.publicProperty.loginModel.User_Type) {
        [_paramsDic setObject:appdelegate.publicProperty.loginModel.User_Type forKey:@"Type"];
    } else {
        [_paramsDic setObject:@"GZ" forKey:@"Type"];
    }
    if (appdelegate.publicProperty.loginModel.Entity_Code) {
        [_paramsDic setObject:appdelegate.publicProperty.loginModel.Entity_Code forKey:@"EntityCode"];
    } else {
        [_paramsDic setObject:@"BXJC" forKey:@"EntityCode"];
    }
    
    if (appdelegate.publicProperty.loactionModel.address) {
        [_paramsDic setObject:appdelegate.publicProperty.loactionModel.address forKey:@"SearchAddress"];
    }
    if (appdelegate.publicProperty.loactionModel.lat) {
        [_paramsDic setObject:appdelegate.publicProperty.loactionModel.lat forKey:@"XAddress"];
    } 
    if (appdelegate.publicProperty.loactionModel.lng) {
        [_paramsDic setObject:appdelegate.publicProperty.loactionModel.lng forKey:@"YAddress"];
    }
    if (appdelegate.publicProperty.loactionModel.state) {
        [_paramsDic setObject:appdelegate.publicProperty.loactionModel.state forKey:@"Province"];
    }
    if (appdelegate.publicProperty.loactionModel.city) {
        [_paramsDic setObject:appdelegate.publicProperty.loactionModel.city forKey:@"City"];
    }
    if (appdelegate.publicProperty.loactionModel.subLocality) {
        [_paramsDic setObject:appdelegate.publicProperty.loactionModel.subLocality forKey:@"County"];
    }
    
    // 请求数据
    [YKNetHelp getDataWithPath:ApiSExternalGetQRInfo andParams:_paramsDic andComplete:^(BOOL success, id result) {
        if (success) {
            [_playerRight play];
            YKProductInfo *productInfo = [YKProductInfo mj_objectWithKeyValues:result[@"Data"]];
            YKCheckController *checkVC = [[YKCheckController alloc] init];
            if ([result[@"Msg"] isEqual:[NSNull null]]) {
                productInfo.noData = YES;
            }
            checkVC.productInfo = productInfo;
            [self presentViewController:checkVC animated:YES completion:nil];
        } else {
            NSLog(@"123");
             [_player play];
        }
    }];
    
}


#pragma mark -- 初始化扫描界面
-(void)setScanview {
    _scanView=[[UIView alloc] initWithFrame:CGRectMake(0,0, kScreenWidth,kScreenheight-64)];
    _scanView.backgroundColor=[UIColor clearColor];
    
    //最上部view
    UIView* upView = [[UIView alloc] initWithFrame:CGRectMake(0,0, kScreenWidth,SCANVIEW_EdgeTop)];
    upView.alpha =TINTCOLOR_ALPHA;
    upView.backgroundColor = [UIColor blackColor];
    [_scanView addSubview:upView];
    
    //左侧的view
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0,SCANVIEW_EdgeTop, SCANVIEW_EdgeLeft,kScreenWidth-2*SCANVIEW_EdgeLeft)];
    leftView.alpha =TINTCOLOR_ALPHA;
    leftView.backgroundColor = [UIColor blackColor];
    [_scanView addSubview:leftView];
    
    /******************中间扫描区域****************************/
    UIImageView *scanCropView=[[UIImageView alloc] initWithFrame:CGRectMake(SCANVIEW_EdgeLeft,SCANVIEW_EdgeTop, kScreenWidth-2*SCANVIEW_EdgeLeft,kScreenWidth-2*SCANVIEW_EdgeLeft)];
    //scanCropView.image=[UIImage imageNamed:@""];
    
    scanCropView.layer.borderColor=[UIColor whiteColor].CGColor;
    scanCropView.layer.borderWidth=2.0;
    
    scanCropView.backgroundColor=[UIColor clearColor];
    [_scanView addSubview:scanCropView];
    
    
    //右侧的view
    UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(kScreenWidth-SCANVIEW_EdgeLeft,SCANVIEW_EdgeTop, SCANVIEW_EdgeLeft,kScreenWidth-2*SCANVIEW_EdgeLeft)];
    rightView.alpha =TINTCOLOR_ALPHA;
    rightView.backgroundColor = [UIColor blackColor];
    [_scanView addSubview:rightView];
    
    
    //底部view
    UIView *downView = [[UIView alloc] initWithFrame:CGRectMake(0,kScreenWidth-2*SCANVIEW_EdgeLeft+SCANVIEW_EdgeTop,kScreenWidth, kScreenheight-(kScreenWidth-2*SCANVIEW_EdgeLeft+SCANVIEW_EdgeTop)-64)];
    //downView.alpha = TINTCOLOR_ALPHA;
    downView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:TINTCOLOR_ALPHA];
    [_scanView addSubview:downView];
    
    //用于说明的label
    _labIntroudction= [[UILabel alloc] init];
    _labIntroudction.backgroundColor = [UIColor clearColor];
    _labIntroudction.frame=CGRectMake(0, kScreenheight-(kScreenWidth-2*SCANVIEW_EdgeLeft+SCANVIEW_EdgeTop)-64 - 150, kScreenWidth,20);
    _labIntroudction.numberOfLines=1;
    _labIntroudction.font=[UIFont systemFontOfSize:22];
    _labIntroudction.textAlignment=NSTextAlignmentCenter;
    _labIntroudction.textColor=[UIColor whiteColor];
    _labIntroudction.text=@"请扫描石膏板侧边上的条形码";
    [downView addSubview:_labIntroudction];
    
//    UIView *darkView = [[UIView alloc] initWithFrame:CGRectMake(0, downView.frame.size.height-100.0,kScreenWidth, 100.0)];
//    darkView.backgroundColor = [[UIColor blackColor]  colorWithAlphaComponent:DARKCOLOR_ALPHA];
//    [downView addSubview:darkView];
    
    //用于开关灯操作的button
    openButton = [[UIButton alloc] initWithFrame:CGRectMake((kScreenWidth - 300) /2,20 + 30, 300.0, 40.0)];
    [openButton setTitle:@"打开闪光灯" forState:UIControlStateNormal];
    [openButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    openButton.layer.masksToBounds = YES;
    openButton.layer.cornerRadius = 4;
    
    openButton.titleLabel.textAlignment=NSTextAlignmentCenter;
    openButton.backgroundColor=kNavigationMainColor;
    openButton.titleLabel.font=[UIFont systemFontOfSize:22.0];
    [openButton addTarget:self action:@selector(openLight)forControlEvents:UIControlEventTouchUpInside];
    [downView addSubview:openButton];
    
    //画中间的基准线
    _codeLine = [[UIView alloc] initWithFrame:CGRectMake(SCANVIEW_EdgeLeft + 20,SCANVIEW_EdgeTop, kScreenWidth- 40 -2*SCANVIEW_EdgeLeft,2)];
    _codeLine.backgroundColor = [UIColor whiteColor];
    [_scanView addSubview:_codeLine];
    
    
    UIImageView *image1 = [[UIImageView alloc] initWithFrame:CGRectMake(-2, -2, 20, 20)];
    image1.image = [UIImage imageNamed:@"icon1"];
    [scanCropView addSubview:image1];
    
    UIImageView *image2 = [[UIImageView alloc] initWithFrame:CGRectMake(scanCropView.frame.size.width - 20 + 2, -2, 20, 20)];
    image2.image = [UIImage imageNamed:@"icon2"];
    [scanCropView addSubview:image2];
    
    UIImageView *image3 = [[UIImageView alloc] initWithFrame:CGRectMake(-2, scanCropView.frame.size.height - 20 + 2, 20, 20)];
    image3.image = [UIImage imageNamed:@"icon3"];
    [scanCropView addSubview:image3];
    
    UIImageView *image4 = [[UIImageView alloc] initWithFrame:CGRectMake(scanCropView.frame.size.width - 20 + 2, scanCropView.frame.size.height - 20 + 2, 20, 20)];
    image4.image = [UIImage imageNamed:@"icon4"];
    [scanCropView addSubview:image4];
}



- (void)openLight
{
    if (_readerView.torchMode == 0) {
        [openButton setTitle:@"关闭闪光灯" forState:UIControlStateNormal];
        _readerView.torchMode = 1;
    }else {
        _readerView.torchMode = 0;
        [openButton setTitle:@"开启闪光灯" forState:UIControlStateNormal];
    }
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    _readerView.torchMode = 0;
    
    [self stopTimer];
    
    [_readerView stop];
    
}
//二维码的横线移动
- (void)moveUpAndDownLine
{
    CGFloat Y=self.codeLine.frame.origin.y;
    //CGRectMake(SCANVIEW_EdgeLeft, SCANVIEW_EdgeTop, VIEW_WIDTH-2*SCANVIEW_EdgeLeft, 1)]
    if (kScreenWidth-2*SCANVIEW_EdgeLeft+SCANVIEW_EdgeTop==Y){
        
        [UIView beginAnimations:@"asa" context:nil];
        [UIView setAnimationDuration:1];
        self.codeLine.frame=CGRectMake(SCANVIEW_EdgeLeft + 20, SCANVIEW_EdgeTop, kScreenWidth - 40 -2*SCANVIEW_EdgeLeft,1);
        [UIView commitAnimations];
    }else if(SCANVIEW_EdgeTop==Y){
        [UIView beginAnimations:@"asa" context:nil];
        [UIView setAnimationDuration:1];
        self.codeLine.frame=CGRectMake(SCANVIEW_EdgeLeft + 20, kScreenWidth-2*SCANVIEW_EdgeLeft+SCANVIEW_EdgeTop, kScreenWidth-2*SCANVIEW_EdgeLeft - 40,1);
        [UIView commitAnimations];
    }
    
}

- (void)createTimer
{
    //创建一个时间计数
    _timer=[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(moveUpAndDownLine) userInfo:nil repeats:YES];
}

- (void)stopTimer
{
    if ([_timer isValid] == YES) {
        [_timer invalidate];
        _timer =nil;
    }
    if ([self.tintColorTimer isValid] == YES) {
        [self.tintColorTimer invalidate];
        self.tintColorTimer =nil;
    }
    
    
}


- (void)createCustomBtn  {
    
    UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, 16, 40, 40)];
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backBtnAction) forControlEvents:UIControlEventTouchUpInside];
    
//    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:backBtn];
//    
//    self.navigationItem.leftBarButtonItem = item;
    
    [self.view addSubview:backBtn];

}
- (void)backBtnAction {
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
//创建改变Label的字的颜色的定时器
- (void)createLableTintColorTimer {
    self.tintColorTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(changeLabelTintColor) userInfo:nil repeats:YES];
    
}
- (void)changeLabelTintColor {
    NSInteger indexCount = _count % 3;
    self.labIntroudction.textColor = self.colorArray[indexCount];
    _count++;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
